package imongo

import (
	"context"
	"fmt"
	"gitee.com/tietang/terrace-go/v2/base"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"time"
)

const (
	timeout = 10 * time.Second
)

var client *mongo.Client
var db *mongo.Database

func MongoClient() *mongo.Client {
	base.Check(client)
	return client
}
func MongoDb() *mongo.Database {
	base.Check(db)
	return db
}

func Ctx() context.Context {
	ctx, _ := context.WithTimeout(context.Background(), timeout)
	return ctx
}

type MongoStarter struct {
	base.BaseStarter
	uri     string
	options options.ClientOptions
	client  *mongo.Client
	db      *mongo.Database
}

const (
	URI = "mongodb://%s/test?w=majority&tz_aware=True"
	uri = "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
)

func (s *MongoStarter) Init(ctx base.StarterContext) {
	host := ctx.Props().GetDefault("mongo.host", "172.16.1.248")
	s.uri = fmt.Sprintf(URI, host)
	ctxTimeout := ctx.Props().GetDurationDefault("mongo.ctxTimeout", 10*time.Second)
	mgm.SetCtxTimeout(ctxTimeout)
}

func (s *MongoStarter) Setup(ctx base.StarterContext) {

	mongoClient, err := mongo.Connect(Ctx(), options.Client().ApplyURI(s.uri))
	if err != nil {
		panic(err)
	}
	if err = mongoClient.Ping(Ctx(), readpref.Primary()); err != nil {
		panic(err)
	}
	dbName := ctx.Props().GetDefault("mongo.database", "terrace")
	db = mongoClient.Database(dbName)
	s.db = db
	s.client = mongoClient
	client = mongoClient

	mgm.SetMongoDatabase(db)
}

func (s *MongoStarter) Stop(ctx base.StarterContext) {
	client.Disconnect(Ctx())
}
